//
//  PpLanguageSwitchTool.swift
//  Palmpilot
//
//  Created by 杨伟毅 on 2018/10/19.
//  Copyright © 2018年 杨伟毅. All rights reserved.
//

import UIKit

let UserLanguage = "UserLanguage"
let AppleLanguages = "AppleLanguages"

class PpLanguageSwitchTool: NSObject {
    static let sharedTool = PpLanguageSwitchTool()
    var bundle:Bundle?
    class func getString(key:String) -> String{
        let bundle = PpLanguageSwitchTool.sharedTool.bundle
        let str = bundle?.localizedString(forKey: key, value: nil, table: nil)
        return str!
    }
    func initUserLanguage() {
        var string:String = ppUserder.value(forKey: UserLanguage) as! String? ?? ""
        if string == "" {
            let languages = ppUserder.object(forKey: AppleLanguages) as? NSArray
            if languages?.count != 0 {
                let current = languages?.object(at: 0) as? String
                if current != nil {
                    string = current!
                    ppUserder.set(current, forKey: UserLanguage)
                    ppUserder.synchronize()
                }
            }
        }
        string = string.replacingOccurrences(of: "-CN", with: "")
        string = string.replacingOccurrences(of: "-US", with: "")
        var path = Bundle.main.path(forResource:string , ofType: "lproj")
        if path == nil {
            path = Bundle.main.path(forResource:"en" , ofType: "lproj")
        }
        bundle = Bundle(path: path!)
    }
    
    func setLanguage(langeuage:String) {
        let path = Bundle.main.path(forResource:langeuage , ofType: "lproj")
        bundle = Bundle(path: path!)
        ppUserder.set(langeuage, forKey: UserLanguage)
        ppUserder.synchronize()
        
    }

    
    

}
